import Message from 'tdesign-miniprogram/message/index';
import { novelAPI } from '~/api/novel';
import { interactionAPI } from '~/api/interaction';
const authUtils = require('~/utils/auth.js');
const apiHelper = require('~/utils/api-helper.js');

Page({
  data: {
    // Tab状态
    currentTab: 'ongoing', // ongoing, completed, activity
    currentSubTab: 'my-participated', // my-participated, recruiting
    
    // 小说列表数据
    myParticipatedNovels: [],
    recruitingNovels: [],
    completedNovels: [],
    
    // 当前显示的小说列表
    currentNovels: [],
    
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      hasMore: true
    },
    
    // 加载状态
    loading: false,
    refreshing: false
  },

  /**
   * 页面加载
   */
  onLoad(options) {
    this.loadInitialData();
  },

  /**
   * 页面显示
   */
  onShow() {
    // 如果用户已登录，刷新我参与的小说列表
    if (authUtils.isLoggedIn()) {
      this.refreshCurrentTabData();
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.refreshCurrentTabData();
    wx.stopPullDownRefresh();
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    this.loadMore();
  },

  /**
   * 加载初始数据
   */
  async loadInitialData() {
    try {
      this.setData({ loading: true });
      
      // 检查登录状态
      if (!authUtils.isLoggedIn()) {
        // 未登录时只显示招募中的小说和完结榜
        await this.loadRecruitingNovels();
        await this.loadCompletedNovels();
        // 设置当前显示为招募中的小说
        this.setData({ 
          currentSubTab: 'recruiting',
          currentNovels: this.data.recruitingNovels 
        });
      } else {
        // 已登录时加载用户参与的小说
        await this.loadMyParticipatedNovels();
        await this.loadRecruitingNovels();
        await this.loadCompletedNovels();
        // 根据当前Tab状态更新显示数据
        this.updateCurrentTabData(this.data.currentTab);
      }
    } catch (error) {
      console.error('加载初始数据失败:', error);
      // 降级到测试数据
      this.setTestData();
      this.updateCurrentTabData(this.data.currentTab);
      
      Message.error({
        context: this,
        content: '加载数据失败，已显示示例数据'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 设置测试数据
   */
  setTestData() {
    const testNovels = [
      {
        id: 1,
        title: "星际迷航：新纪元",
        tags: "科幻",
        description: "在遥远的未来，人类踏上了征服星辰大海的征程...",
        coverUrl: "",
        status: 2,
        creationType: 2,
        currentChapterCount: 5,
        targetChapterCount: 20,
        likeCount: 23,
        commentCount: 8,
        favoriteCount: 12,
        isParticipant: true,
        participants: [
          { userId: 1, avatarUrl: "", nickname: "作者1" },
          { userId: 2, avatarUrl: "", nickname: "作者2" },
          { userId: 3, avatarUrl: "", nickname: "作者3" }
        ]
      },
      {
        id: 2,
        title: "古风奇缘",
        tags: "古风",
        description: "一段跨越千年的爱恋，一场命运的邂逅...",
        coverUrl: "",
        status: 1,
        creationType: 2,
        currentChapterCount: 0,
        targetChapterCount: 15,
        likeCount: 15,
        commentCount: 3,
        favoriteCount: 8,
        isParticipant: false,
        participants: [
          { userId: 4, avatarUrl: "", nickname: "古风作者" }
        ]
      }
    ];

    const completedNovels = [
      {
        id: 3,
        title: "修仙传说",
        tags: "仙侠",
        description: "一个凡人踏上修仙之路的传奇故事...",
        coverUrl: "",
        status: 3,
        creationType: 1,
        currentChapterCount: 50,
        likeCount: 156,
        commentCount: 45,
        favoriteCount: 89,
        creatorNickname: "修仙大师"
      }
    ];

    this.setData({
      myParticipatedNovels: testNovels,
      recruitingNovels: [testNovels[1]],
      completedNovels: completedNovels,
      hasMore: false
    });

    // 根据当前Tab状态更新显示数据
    this.updateCurrentTabData(this.data.currentTab);
    
    console.log('测试数据已设置:', this.data);
  },

  /**
   * 切换主Tab
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab === this.data.currentTab) return;

    this.setData({ 
      currentTab: tab,
      pagination: { page: 1, pageSize: 10, hasMore: true }
    });

    // 根据tab更新当前显示的数据
    this.updateCurrentTabData(tab);
  },

  /**
   * 更新当前Tab显示的数据
   */
  updateCurrentTabData(tab) {
    const { myParticipatedNovels, recruitingNovels, completedNovels, currentSubTab } = this.data;
    
    switch (tab) {
      case 'ongoing':
        const currentNovels = currentSubTab === 'my-participated' ? myParticipatedNovels : recruitingNovels;
        this.setData({ currentNovels });
        break;
      case 'completed':
        this.setData({ currentNovels: completedNovels });
        break;
      case 'activity':
        this.setData({ currentNovels: [] });
        break;
    }
  },

  /**
   * 切换子Tab
   */
  switchSubTab(e) {
    const subTab = e.currentTarget.dataset.subtab;
    if (subTab === this.data.currentSubTab) return;

    this.setData({ 
      currentSubTab: subTab,
      pagination: { page: 1, pageSize: 10, hasMore: true }
    });

    // 更新当前显示的数据
    const { myParticipatedNovels, recruitingNovels } = this.data;
    const currentNovels = subTab === 'my-participated' ? myParticipatedNovels : recruitingNovels;
    this.setData({ currentNovels });
  },

  /**
   * 加载Tab数据
   */
  async loadTabData(tab) {
    try {
      this.setData({ loading: true });
      
      switch (tab) {
        case 'ongoing':
          await this.loadSubTabData(this.data.currentSubTab);
          break;
        case 'completed':
          await this.loadCompletedNovels();
          break;
        case 'activity':
          // 活动区暂时无数据
          break;
      }
    } catch (error) {
      console.error('加载Tab数据失败:', error);
      Message.error({
        context: this,
        content: '加载数据失败，请重试'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 加载子Tab数据
   */
  async loadSubTabData(subTab) {
    switch (subTab) {
      case 'my-participated':
        await this.loadMyParticipatedNovels();
        break;
      case 'recruiting':
        await this.loadRecruitingNovels();
        break;
    }
  },

  /**
   * 加载我参与的小说
   */
  async loadMyParticipatedNovels(isLoadMore = false) {
    if (!authUtils.isLoggedIn()) {
      this.setData({ 
        myParticipatedNovels: [],
        currentNovels: []
      });
      return;
    }

    try {
      const { pagination } = this.data;
      const page = isLoadMore ? pagination.page + 1 : 1;
      
      const response = await novelAPI.getMyParticipatedNovels({
        page,
        pageSize: pagination.pageSize
      });

      if (response.code === 200) {
        const novels = response.data || [];
        // 使用API辅助工具处理小说数据
        const processedNovels = apiHelper.processNovelList(novels).map(novel => ({
          ...novel,
          isParticipant: true // 我参与的小说标记
        }));
        
        const updatedNovels = isLoadMore ? 
          [...this.data.myParticipatedNovels, ...processedNovels] : processedNovels;

        this.setData({
          myParticipatedNovels: updatedNovels,
          currentNovels: this.data.currentSubTab === 'my-participated' ? updatedNovels : this.data.currentNovels,
          pagination: {
            ...pagination,
            page,
            hasMore: novels.length === pagination.pageSize
          }
        });
      } else {
        throw new Error(response.message || '加载失败');
      }
    } catch (error) {
      console.error('加载我参与的小说失败:', error);
      throw error;
    }
  },

  /**
   * 加载正在招募的小说
   */
  async loadRecruitingNovels(isLoadMore = false) {
    try {
      const { pagination } = this.data;
      const page = isLoadMore ? pagination.page + 1 : 1;
      
      const response = await novelAPI.getRecruitingNovels({
        page,
        pageSize: pagination.pageSize
      });

      if (response.code === 200) {
        const novels = response.data || [];
        // 使用API辅助工具处理小说数据
        const processedNovels = apiHelper.processNovelList(novels);
        
        const updatedNovels = isLoadMore ? 
          [...this.data.recruitingNovels, ...processedNovels] : processedNovels;

        this.setData({
          recruitingNovels: updatedNovels,
          currentNovels: this.data.currentSubTab === 'recruiting' ? updatedNovels : this.data.currentNovels,
          pagination: {
            ...pagination,
            page,
            hasMore: novels.length === pagination.pageSize
          }
        });
      } else {
        throw new Error(response.message || '加载失败');
      }
    } catch (error) {
      console.error('加载正在招募的小说失败:', error);
      throw error;
    }
  },

  /**
   * 加载已完结小说
   */
  async loadCompletedNovels(isLoadMore = false) {
    try {
      const { pagination } = this.data;
      const page = isLoadMore ? pagination.page + 1 : 1;
      
      const response = await novelAPI.getCompletedNovels({
        page,
        pageSize: pagination.pageSize
      });

      if (response.code === 200) {
        const novels = response.data || [];
        // 使用API辅助工具处理小说数据
        const processedNovels = apiHelper.processNovelList(novels);
        
        const updatedNovels = isLoadMore ? 
          [...this.data.completedNovels, ...processedNovels] : processedNovels;

        this.setData({
          completedNovels: updatedNovels,
          currentNovels: this.data.currentTab === 'completed' ? updatedNovels : this.data.currentNovels,
          pagination: {
            ...pagination,
            page,
            hasMore: novels.length === pagination.pageSize
          }
        });
      } else {
        throw new Error(response.message || '加载失败');
      }
    } catch (error) {
      console.error('加载已完结小说失败:', error);
      throw error;
    }
  },

  /**
   * 刷新当前Tab数据
   */
  async refreshCurrentTabData() {
    try {
      this.setData({ 
        refreshing: true,
        pagination: { page: 1, pageSize: 10, hasMore: true }
      });
      
      await this.loadTabData(this.data.currentTab);
    } catch (error) {
      console.error('刷新数据失败:', error);
    } finally {
      this.setData({ refreshing: false });
    }
  },

  /**
   * scroll-view 下拉刷新事件处理
   */
  onRefresh() {
    this.refreshCurrentTabData();
  },

  /**
   * 加载更多
   */
  async loadMore() {
    const { pagination, loading } = this.data;
    if (loading || !pagination.hasMore) return;

    try {
      this.setData({ loading: true });
      
      const { currentTab, currentSubTab } = this.data;
      if (currentTab === 'ongoing') {
        if (currentSubTab === 'my-participated') {
          await this.loadMyParticipatedNovels(true);
        } else {
          await this.loadRecruitingNovels(true);
        }
      } else if (currentTab === 'completed') {
        await this.loadCompletedNovels(true);
      }
    } catch (error) {
      console.error('加载更多失败:', error);
      Message.error({
        context: this,
        content: '加载更多失败，请重试'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 创建小说
   */
  onCreateNovel() {
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    wx.navigateTo({
      url: '/pages/novel-create/index'
    });
  },

  /**
   * 点击小说卡片
   */
  onNovelTap(e) {
    const novelId = e.currentTarget.dataset.novelId;
    wx.navigateTo({
      url: `/pages/novel-detail/index?novelId=${novelId}`
    });
  },

  /**
   * 加入小说
   */
  async onJoinNovel(e) {
    // 安全地调用stopPropagation
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const novelId = e.currentTarget.dataset.novelId;
    
    try {
      const response = await novelAPI.joinNovel(novelId);
      if (response.code === 200) {
        Message.success({
          context: this,
          content: '加入成功！'
        });
        
        // 刷新列表
        this.refreshCurrentTabData();
      }
    } catch (error) {
      console.error('加入小说失败:', error);
      Message.error({
        context: this,
        content: error.message || '加入失败，请重试'
      });
    }
  },

  /**
   * 写下一章
   */
  async onWriteChapter(e) {
    // 安全地调用stopPropagation
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const novelId = e.currentTarget.dataset.novelId;
    
    try {
      // 检查是否可以写作
      const canWriteResponse = await novelAPI.canWriteNextChapter(novelId);
      if (canWriteResponse.code === 200 && canWriteResponse.data) {
        wx.navigateTo({
          url: `/pages/chapter-write/index?novelId=${novelId}`
        });
      } else {
        Message.warning({
          context: this,
          content: '今日已写过章节，请明日再来'
        });
      }
    } catch (error) {
      console.error('检查写作权限失败:', error);
      Message.error({
        context: this,
        content: '检查写作权限失败，请重试'
      });
    }
  },

  /**
   * 继续写作（单人创作）
   */
  onContinueWriting(e) {
    // 安全地调用stopPropagation
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    if (!authUtils.isLoggedIn()) {
      authUtils.redirectToLogin();
      return;
    }

    const novelId = e.currentTarget.dataset.novelId;
    wx.navigateTo({
      url: `/pages/chapter-write/index?novelId=${novelId}`
    });
  },

  /**
   * 阅读小说
   */
  onReadNovel(e) {
    // 安全地调用stopPropagation
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    const novelId = e.currentTarget.dataset.novelId;
    wx.navigateTo({
      url: `/pages/novel-detail/index?novelId=${novelId}`
    });
  }
});